<template>
    <w-pop ref="pop" :direction="'btt'" :showHeader="false" :closeModal="false">
        <el-icon class="close_icon" size="52" color="#fff" @click="handleClose">
            <CircleClose />
        </el-icon>
        <div class="product_pop_container">
            <div class="header">
                <div class="cover">
                    <img :src="itemObj.imageUrl" v-onerror alt="" srcset="" />
                </div>
                <div class="detail">
                    <div class="name">{{ itemObj.productName }}</div>
                    <div class="nums_control">
                        <button @click="handleMinus"><b>-</b></button>
                        <el-input readonly v-model="itemObj.InputTotal" size="default" type="tel" class="nums"></el-input>
                        <button @click="handleAdd"><b>+</b></button>
                    </div>
                </div>
            </div>
            <div class="title" :class="{ error: itemObj.currentTotal > itemObj.singleTotal }">{{ $t("detail.select") }}({{
                itemObj.currentTotal }}/{{ itemObj.singleTotal }})</div>
            <div class="taste_container">
                <div class="taste_item" v-for="item in list.skuVos" :key="item.id">
                    <div class="name">
                        {{ item.skuName }}
                    </div>
                    <w-nums v-model="item.defaultNumber" @add="add(item)" @reduce="reduce(item)"></w-nums>
                </div>
            </div>
            <div class="comfir_btn">
                <el-button type="primary" size="default" round @click="handleAddBiy">{{ $t("login.comfir") }}</el-button>
            </div>
        </div>
    </w-pop>
</template>

<script>
import { defineComponent, ref, watch } from "vue";
import { getPrudoctMySelf } from '@/api/mall'
import { useI18n } from "vue-i18n";
import { ElMessage, ElMessageBox } from "element-plus";
import storage from '@/utils/storage';
export default defineComponent({
    props: {},
    components: {},
    setup(props, { emit }) {
        const { t } = useI18n()
        const pop = ref();
        // 顶部
        const itemObj = ref({})
        // sku 
        const list = ref({})

        const handleClose = () => {
            ElMessageBox.confirm(
                t('error.tips6'),
                '提示',
                {
                    confirmButtonText: '確認',
                    cancelButtonText: '取消',
                    type: 'warning',
                    showClose: false,
                    closeOnClickModal: false
                }
            ).then(() => {
                pop.value.close();
            })
        }
        const open = async (id, item) => {
            // 打开之前检查缓存是否有添加过商品
            const arr = storage.getStorage('adds')
            const ishave = arr && arr.find(el => el.id === id);
            console.log(ishave, arr, id, 'ishave--------本地是否存在选过sku')

            if (ishave) {
                // 存在不掉接口从本都取出来数据
                list.value = ishave.list
                itemObj.value = ishave.itemObj
            } else {

                itemObj.value = { ...item }
                console.log(itemObj.value, '-itempbj')
                // 不存在调用接口获取sku
                //  2 订餐计划(订餐计划没有sku选只有数量)
                // 1 周订餐           0 零售批发
                // 获取自选SKU ;  
                const res = await getPrudoctMySelf({ id })
                if (res) {
                    list.value = res
                    list.value.skuVos.forEach(el => {
                        el.defaultNumber = el.leastNum
                    })
                    // 基数*顶部输入框的数
                    itemObj.value.singleTotal = list.value.total * itemObj.value.InputTotal
                }
            }
            pop.value.open();
        };
        // sku加
        const add = (item) => {
            // 周计划没有大小限制 零售才有大小限制
            if (itemObj.value.productType == 1) {
                item.defaultNumber += 1
            } else {
                item.defaultNumber += 1
                if (item.defaultNumber > item.maxNum) {
                    item.defaultNumber = item.maxNum
                    ElMessage({ type: 'warning', message: '超过最大数量' })
                }
            }
            // 求和
            handleCalculateTotal()
        }
        // sku减
        const reduce = (item) => {
            // 周计划没有大小限制 零售才有大小限制
            if (itemObj.value.productType == 1) {
                item.defaultNumber -= 1
                if (item.defaultNumber <= 0) {
                    item.defaultNumber = 0
                }
            } else {
                item.defaultNumber -= 1
                if (item.defaultNumber < item.leastNum) {
                    item.defaultNumber = item.leastNum
                    ElMessage({ type: 'warning', message: `最少购买${item.leastNum}` })
                }
            }
            // 求和
            handleCalculateTotal()

        }
        // 顶部加
        const handleAdd = () => {
            itemObj.value.InputTotal += 1
            itemObj.value.singleTotal = itemObj.value.InputTotal * list.value.total
        }
        // 顶部减
        const handleMinus = () => {
            itemObj.value.InputTotal -= 1
            if (itemObj.value.InputTotal <= 1) {
                itemObj.value.InputTotal = 1
            }
            itemObj.value.singleTotal = itemObj.value.InputTotal * list.value.total
        }

        // sku计算总和
        const handleCalculateTotal = () => {
            const total = list.value.skuVos.reduce((accumulator, currentValue) => accumulator + currentValue.defaultNumber, 0);
            itemObj.value.currentTotal = total
        }
        // 检查本地sku并且缓存
        const checkLocalSkuAndSave = () => {
            // 从本地取出缓存
            const arr = storage.getStorage('adds') || []
            // 如果本地有取出来重新赋值
            const ishaveItem = arr && arr.find(el => el.id === itemObj.value.id);
            console.log(ishaveItem, 'ishaveItem---本地之前存在sku更新并且缓存')
            if (ishaveItem) {
                arr.forEach(el => {
                    if (el.id == itemObj.value.id) {
                        el.list = list.value
                        el.itemObj = itemObj.value
                    }
                })
            } else {
                console.log(ishaveItem, 'ishaveItem---本地之前不存存在sku更新并且缓存')
                arr.push({
                    id: itemObj.value.id,
                    list: list.value,
                    itemObj: itemObj.value
                })
            }
            storage.setStorage('adds', arr)
        }
        //确认
        const handleAddBiy = () => {
            console.log(itemObj.value, list.value)
            if (itemObj.value.currentTotal != itemObj.value.singleTotal) {
                ElMessage({
                    type: 'warning',
                    message: t('error.tips7')
                })
                return
            }
            checkLocalSkuAndSave()
            ElMessage({
                type: 'success',
                message: t('error.tips8')
            })
            pop.value.close();
            emit('addBuySucc')
        }
        return {
            list,
            itemObj,
            pop,
            add,
            open,
            reduce,
            handleClose,
            handleAdd,
            handleMinus,
            handleAddBiy
        };
    },
});
</script>

<style scoped lang="scss">
.product_pop_container {
    .header {
        display: flex;
        height: 91px;
        overflow: hidden;
        padding: 20px 16px;
        border-bottom: 1px solid rgba(0, 0, 0, 0.12);

        .cover {
            height: 91px;
            width: 91px;

            img {
                width: 91px;
                height: 91px;
            }
        }

        .detail {
            margin-left: 9.6px;

            .name {
                color: #333;
                font-family: Helvetica;
                font-size: 18px;
                font-style: normal;
                font-weight: 400;
                line-height: 20px;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .nums_control {
                display: flex;
                margin-top: 10px;
                flex-direction: row;

                button {
                    width: 50px;
                    height: 40px;
                    background: #fff;
                    border-radius: 0;
                    border: 1px solid rgba(0, 0, 0, 0.12);

                    b {
                        font-size: 18px;
                        color: #000;
                    }
                }

                .nums {
                    margin: 0 8px;
                }

                ::v-deep(.el-input__inner) {
                    text-align: center;
                    font-weight: bold;
                    color: #000;
                }
            }

        }
    }

    .title {
        color: #666;
        font-family: Helvetica;
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
        margin: 16px;
    }

    .error {
        color: red;
    }

    .taste_container {
        min-height: 100px;
        max-height: 400px;
        overflow-y: auto;

        .taste_item {
            padding: 20px 0px 16px 0px;
            color: #333;
            font-family: Helvetica;
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
            border-bottom: 1px solid rgba(0, 0, 0, 0.08);
            margin: 0 16px;
            display: flex;
            flex-direction: row;
            align-items: center;

            .name {
                width: 100%;
            }

            .nums_control {
                display: flex;
                height: 30px;
                border: 1px solid #ccc;
                border-radius: 2px;
                line-height: 30px;
                width: 120px;
                align-items: center;
                justify-content: center;

                input {
                    border: none;
                    width: 20px;
                    font-size: 16px;
                    text-align: center;
                    font-weight: bold;
                    color: #000;
                }
            }


        }


    }

    .comfir_btn {
        padding: 16px;

        button {
            width: 100%;
            height: 48px;
            border-radius: 50px;
        }
    }


}


.close_icon {
    position: absolute;
    right: 16px;
    top: -80px;
    z-index: 10000;
}
</style>
